<!--
 * @Author yuec621@outLook.com
 * @Description: 曲线配置组件
 * @Date: 2024-11-04 13:34:02
 * @LastEditTime: 2025-05-15 13:15:13
 * @LastEditors: Please set LastEditors
 * @Reference: 
-->
<template>
    <el-drawer v-model="state.drawerShow" direction="rtl" size="50%" :close-on-click-modal="true" :modal="true">
        <template #header="{ close, titleId, titleClass }">
            <h4 class="mask_sub_title">
                <svg-icon icon-class="biaotitubiao" /><span>曲线配置</span></h4>
        </template>
        <div class="lineConfigBox">
            <!-- 保存模板卡片 -->
            <saveTempCom @submitForm="submitForm" :tempShow="state.tempShow" :tempList="state.rightList"></saveTempCom>
            <!-- 查询历史卡片 -->
            <hisSearchList :style="{position: 'absolute',left:state.serXY.x+'px',top:state.serXY.y+'px',zIndex:11}"
                @clearSaveClick="clearSaveClick" @searsubmitClick="searsubmitClick" :searList="state.searList"
                v-if="state.searListShow" @searcancelClick="searcancelClick"></hisSearchList>
            <!-- 使用模板卡片 -->
            <useTempCom :style="{position: 'absolute',
            left:state.useTempXY.x+'px',top:state.useTempXY.y+'px',zIndex:11}" @delUseTempClick="delUseTempClick"
                :tableData="state.tableData" @submitUseTempClick="submitUseTempClick" v-if="state.useTempShow">
            </useTempCom>
            <!-- 筛选搜索列表卡片 -->
            <searchListCom :noLeftshow="true" :style="{position: 'absolute',
            left:state.shuaiXY.x+'px',top:state.shuaiXY.y+'px',zIndex:11}" v-if="state.shuaiShow"
                :searList="state.searListSearch" :lineConParams="lineConParams.type"
                @submitSearchResultClick="submitSearchResultClick" @radioChange="radioChange"></searchListCom>
            <el-row :gutter="23">
                <el-col :span="24">
                    <el-row :gutter="24">
                        <el-col :span="12">
                            <div class="tabdiyBox">
                                <span class="hover" v-for="item in tabList" :key="item.type" @click="tabClick(item)"
                                    :class="state.tabType == item.type ?'active':''">{{item.name}}</span>
                                <span class="btnSpan" v-if="state.tabType ==1" ref="shuaixuanRef"
                                    @click="shuaixuanClick" style="z-index: 3;">
                                    <svg-icon icon-class="shaixuan" />筛选</span>
                            </div>
                        </el-col>
                        <el-col :span="4">

                        </el-col>
                        <el-col :span="8" v-if="state.tabType ==1 || state.tabType ==11 || state.tabType ==111">
                            <div class="btnSpanList">
                                <span class="btnSpan" ref="searListRef" @click="hisListClick">
                                    <svg-icon icon-class="shijian" />查询历史</span>
                                <span ref="usetempRef" class="btnSpan" @click="usetempClick">
                                    <svg-icon icon-class="moban" />使用模板</span>
                            </div>
                        </el-col>
                        <el-col :span="24">
                            <acSearListCom :acSearList="state.acsearList" @clearAllClick="clearAllClick"
                                @acSearchChange="submitSearchResultClick">
                            </acSearListCom>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <el-row :gutter="23" v-if="state.tabType ==1">
                <el-col :span="12">
                    <div class="colgrid" style="position: relative;">
                        <div class="tableListTotal">
                            <span class="tableTile">测点列表<span v-if="noconnected"
                                    style="color: rgba(62, 70, 79, 0.8);margin-left: 5px;">
                                    只显示关联
                                    <el-switch style="margin-left: 5px;" @change="switchChange"
                                        v-model="state.queryObj.isConnected" /></span></span>
                            <span class="tableNum">{{state.rightListadjust.length}}/
                                {{state.leftListnum}}</span>
                        </div>
                        <vxe-grid @checkbox-change="selectChangeEvent" @checkbox-all="selectChangeEventAll"
                            ref="leftTable" stripe @cell-mouseenter="cellmouseenter" v-bind="{
                                 border: 'inner',
                                 stripe: true,
                                 loading:state.tableloading,
  height: '500',
  checkboxConfig: {
    checkMethod: checkSelectMethod
  },
  columns: [
     { type: 'checkbox', width: 60 },
    { field: 'pointId', title: '测点号' , slots: { default: 'pointIdDefault' } },
    { field: 'sensorName', title: '设备名称' },
    { field: 'placeName', title: '安装地点'}
  ],
  data: state.leftList
                            }">
                            <template #pointIdDefault="{ row }">
                                {{ row.pointId }}
                                <svg-icon v-if="row.connectPointDtoList.length>0&&noconnected"
                                    style="fill:rgb(68, 136, 255)" icon-class="guanlian" />
                            </template>
                            <template #empty>
                                <span class="nodataClass">
                                    <img src="@/assets/images/nodata.png">
                                    <p>暂未查询到结果</p>
                                </span>
                            </template>
                        </vxe-grid>
                        <!-- 关联测点列表小弹框 -->
                        <connectPointCom @mouseleave="cellmouseleave"
                            v-if="state.connectPointDtoObj.list.length>0&&noconnected"
                            :connectPointDtoList="state.connectPointDtoObj.list" style="position: absolute;width: 95%"
                            :style="{
            top:state.connectPointDtoObj.y+'px',
            left:state.connectPointDtoObj.x+'px',
            zIndex:9
        }" @connectPointClick="connectPointClick"></connectPointCom>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="colgrid">
                        <div class="tableListTotal" style="display: flex;align-items: center;">
                            <span class="tableTile">已选测点
                                <span class="tableNum">还可选择 <em>{{6-state.rightList.length}}</em>
                                    个测点</span>
                            </span>
                            <span class="tableNum">
                                <svg-icon icon-class="shanchu" class="hover" @click="removerRightClick()" />
                            </span>
                        </div>
                        <vxe-grid stripe v-bind="{
                                 border: 'inner',
                                 stripe: true,
  height: '500',
  checkboxConfig: {
    checkMethod: checkSelectMethod
  },
  columns: [
    { field: 'pointId', title: '测点号' },
    { field: 'sensorName', title: '设备名称' },
    { field: 'placeName', title: '安装地点'},
    { field: 'remove', title: '移除' , slots: { default: 'removeDefault' } },
  ],
  data: state.rightList
                            }">
                            <template #removeDefault="{ row }">
                                <svg-icon class="hover" icon-class="tubiaoneiguanbi" @click="removeClick(row)" />
                            </template>
                            <template #empty>
                                <span class="nodataClass">
                                    <img src="@/assets/images/nodata.png">
                                    <p>暂未查询到结果</p>
                                </span>
                            </template>
                        </vxe-grid>

                    </div>
                </el-col>
            </el-row>
            <chartattr v-if="state.tabType ==2" :attrList="state.attrList" @submitClickattr="submitClickattr"
                :chartType="chartType" :attrObj="attrObj">
            </chartattr>
            <div class="form_footer" style="display: flex;justify-content: space-between">
                <span>
                    <el-button type="success" @click="tempSaveClick">保存为模板</el-button>
                </span>
                <span>
                    <el-button type="info" @click="cancelClick">取消</el-button>
                    <el-button type="primary" @click="submitClick">确定</el-button>
                </span>
            </div>
        </div>
    </el-drawer>
</template>
<script setup>
    import {
        computed,
        nextTick,
        reactive,
        inject,
        watchEffect,
        onMounted,
        watch
    } from 'vue';
    import axios from "@/utils/request"
    import useUserStore from "@/store/modules/user";
    import chartattr from "./chartattr.vue";
    import saveTempCom from "./saveTempCom.vue";
    import hisSearchList from "./hisSearchList.vue";
    import useTempCom from "./useTempCom.vue";
    import connectPointCom from "./connectPointCom.vue";
    import searchListCom from '@/components/commonCom/searchListCom';
    import acSearListCom from '@/components/commonCom/acSearListCom';
    import _ from 'lodash'
    const {
        proxy
    } = getCurrentInstance();
    const userStore = useUserStore();
    const emits = defineEmits(['lineChange'])
    const searListRef = ref(null)
    const props = defineProps({
        timeRange: { //从默认页面来的已选的筛选条件
            type: Array,
            default: () => {
                return []
            }
        },
        acSearchList: { //从默认页面来的已选的筛选条件
            type: Array,
            default: () => {
                return []
            }
        },
        chartType: { //模拟量1、开关量2、累计量类型
            type: Number,
            default: () => {
                return 1
            }
        },
        drawerShow: { //控制弹框显示隐藏
            type: Boolean,
            default: () => {
                return false
            }
        },
        noconnected: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        lineConParams: {
            type: Object,
            default: () => {}
        },
        attrObj: {
            type: Object,
            default: () => {}
        },
        searList: {
            type: Array,
            default: () => {
                return []
            }
        },
        tabList: {
            type: Array,
            default: () => {
                return [{
                    type: 1,
                    name: '测点选择'
                }, {
                    type: 2,
                    name: '属性'
                }]
            }
        },
        lengedList: {
            type: Array,
            default: () => {
                return []
            }
        },
    })
    // 重点
    const state = reactive({
        tableloading:false,
        connectPointDtoObj: {
            list: [],
            x: 0,
            y: 0
        },
        drawerShow: false,
        tabList: [{
            type: 1,
            name: '测点选择'
        }, {
            type: 2,
            name: '属性'
        }],
        tabType: 1,
        leftList: [], //左侧测点列表
        leftListnum: 0,
        rightList: [], //右侧全部数据显示
        rightListadjust: [], //用于判断切换测点列表数量显示

        queryObj: {
            isConnected: false,
            condition: '',
            flag: false,
            type: props.lineConParams.type
        },
        tempShow: false,
        searList: [],
        searListSearch: computed(() => props.searList), //传值给搜索卡片
        searListShow: false,
        serXY: {
            x: undefined,
            y: undefined
        },
        useTempShow: false,
        useTempXY: {
            x: undefined,
            y: undefined
        },
        tableData: [],
        shuaiXY: {
            x: undefined,
            y: undefined
        },
        shuaiShow: false,
        acsearList: [],
        rightListone: [], //模拟量右侧列表显示
        rightListtwo: [], //开关量右侧列表显示
        rightListthree: [], //累计量右侧列表显示
        attrList: [],
        attrObj: undefined,
        clearType: undefined,
        lengedList: []
    })
    let lineConParams = computed(() => {
        return props.lineConParams
    })
    // 筛选量程和自适应事件
    function radioChange(val) {
        emits('radioChange', val)
    }
    // 只显示关联
    function switchChange(val) {
        getList(state.queryObj)
    }

    function tabClick(item) {
        let colors = ['rgba(68, 170, 255, 1)', 'rgba(212, 63, 63, 1)', 'rgba(42, 130, 228, 1)', 'rgba(121, 72, 234, 1)']
        state.tabType = item.type
        state.queryObj.condition = undefined
        if (state.rightList.length > 0) {
            let arr = []
            state.rightList.forEach((item, index) => {
                if (props.chartType == 1) {
                    arr.push({
                        pointId: item.pointId,
                        linechart: '曲线' + item.pointId + '-最大值',
                        type: 'max',
                        lineWidth: 2,
                        lineType: 'solid',
                        lineColor: item.maxlineColor ? item.maxlineColor : colors[index],
                        chartType: false,
                        dotSwitch: false
                    }, {
                        pointId: item.pointId,
                        linechart: '曲线' + item.pointId + '-最小值',
                        type: 'min',
                        lineWidth: 2,
                        lineType: 'solid',
                        lineColor: item.minlineColor ? item.minlineColor : colors[index],
                        chartType: false,
                        dotSwitch: false
                    }, {
                        pointId: item.pointId,
                        linechart: '曲线' + item.pointId + '-平均值',
                        type: 'avg',
                        lineWidth: 2,
                        lineType: 'solid',
                        lineColor: item.avglineColor ? item.avglineColor : colors[index],
                        chartType: false,
                        dotSwitch: false
                    })
                } else if (props.chartType == 2) {
                    arr.push({
                        type: 'max',
                        pointId: item.pointId,
                        linechart: item.pointId,
                        lineColor: item.maxlineColor ? item.maxlineColor : colors[index]
                    })
                }
            })
            state.attrList = arr
        }
        if (item.type == 2) {
            state.rightList = state.rightList
        }
    }
    // 关联测点鼠标悬浮操作
    function cellmouseenter(e) {
        state.connectPointDtoObj.x = 10
        state.connectPointDtoObj.y = e.$event.clientY - 210
        if (e.row.connectPointDtoList.length > 0) {
            state.connectPointDtoObj.list = e.row.connectPointDtoList
        } else {
            state.connectPointDtoObj.list = []
        }
    }

    function cellmouseleave() {
        state.connectPointDtoObj.list = []
    }
    // 关联列表选择
    function connectPointClick(item) {
        if (item.show) {
            state.rightList = state.rightList.filter(itemsub => itemsub.pointId !== item.pointId);
            state.rightList.push(item)
            state.rightList = _.uniqBy(state.rightList, 'pointId')
        } else {
            state.rightList = state.rightList.filter(itemsub => itemsub.pointId !== item.pointId);
        }
    }

    // 列表复选操作
    function selectChangeEventAll(e) {
        if (e.records.length >= 6) {
            proxy.$modal.msgWarning('最多只能选择6个测点!');
            state.rightList = e.records.splice(0, 6)
            state.leftList = e.records
            state.rightListadjust = state.rightList
        } else {
            state.rightList.push(...e.records)
            state.rightList = _.uniqBy(state.rightList, 'pointId')
            state.rightListadjust = state.rightList
            state.leftList = []
        }
    }
    const checkSelectMethod = ({
        row
    }) => {
        // 如果已选中数量小于6或者当前行已被选中，则允许选中
        return state.rightList.length < 6 || state.rightList.includes(row);
    };
    const selectChangeEvent = ({
        records
    }) => {
        state.leftList = _.differenceBy(state.leftList, records, 'pointId')
        state.rightList.push(...records)
        state.rightListadjust.push(...records)
    }
    // 移除操作按钮事件
    function removeClick(row) {
        proxy.$refs['leftTable'].clearCheckboxRow()
        state.rightList = _.differenceBy(state.rightList, [row], 'pointId')
        state.rightListadjust = _.differenceBy(state.rightListadjust, [row], 'pointId')
        nextTick(() => {
            getList(state.queryObj)
        })
    }
    // 删除右侧全部列表
    function removerRightClick() {
        // 获取表格实例，然后设置 selected 为空数组
        proxy.$refs['leftTable'].clearCheckboxRow()
        state.rightList = []
        props.lengedList = []
        state.rightListadjust = []
        getList(state.queryObj)
    }
    // 获取列表数据接口
    function getList(data) {
        state.tableloading=true
        axios.post(lineConParams.value.pointUrl, data).then(
            res => {
                 state.tableloading=false
                state.leftList = res.data
                state.leftListnum = res.data.length
                let arr = state.rightList.map(itemsub => {
                    return itemsub.pointId
                })
                state.leftList = state.leftList.filter((x) => arr.every((y) => y != x.pointId))
            })
    }
    // 取消
    function cancelClick() {
        state.drawerShow = false
    }

    function submitClickattr(data) {
        state.attrObj = data
    }
    // 提交
    function submitClick(data) {
        let rightListdata = state.rightList
        if (rightListdata.length > 0) {
            rightListdata.forEach(item => {
                if (state.attrList.length > 0) {
                    state.attrList.forEach(itemsub => {
                        if (item.pointId == itemsub.pointId) {
                            if (itemsub.type == 'max') {
                                item.maxlineWidth = itemsub.lineWidth
                                item.maxlineType = itemsub.lineType
                                item.maxlineColor = itemsub.lineColor
                                item.maxchartType = itemsub.chartType
                                item.maxdotSwitch = itemsub.dotSwitch
                            }
                            if (itemsub.type == 'min') {
                                item.minlineWidth = itemsub.lineWidth
                                item.minlineType = itemsub.lineType
                                item.minlineColor = itemsub.lineColor
                                item.minchartType = itemsub.chartType
                                item.mindotSwitch = itemsub.dotSwitch
                            }
                            if (itemsub.type == 'avg') {
                                item.avglineWidth = itemsub.lineWidth
                                item.avglineType = itemsub.lineType
                                item.avglineColor = itemsub.lineColor
                                item.avgchartType = itemsub.chartType
                                item.avgdotSwitch = itemsub.dotSwitch
                            }
                        }
                    })
                }
            })
            let datapoint = rightListdata.map(item => {
                return item.pointId
            })
            if (state.tabType != 2) {
                axios.post(lineConParams.value.hisSearchSave, {
                    pointIds: datapoint.join(';')
                }).then(res => {
                    proxy.$modal.msgSuccess(res.msg);
                })
            }
            state.drawerShow = undefined
            props.drawerShow = undefined

            emits('submitPointListClick', rightListdata, state.attrObj)
        } else {
            proxy.$modal.msgWarning('请选择所要查询的测点编号!');
        }
    }

    function tempSaveClick() {
        if (state.rightList.length == 0) {
            proxy.$modal.msgWarning('请先选择测点');
            state.tempShow = false
        } else {
            state.tempShow = new Date()
        }
    }
    // 保存为模版确定按钮
    function submitForm(data) {
        data.pointIds = data.pointIds.join(';')
        axios.post(lineConParams.value.addTemSave, data).then(
            res => {
                proxy.$modal.msgSuccess(res.msg);
                state.tempShow = false
                getuseTempList()
            })
    }
    // 查询历史数据
    const getinfosearchlistSwitch = (data) => {
        return axios({
            url: '/simulate/history/attainPointInfo',
            method: 'post',
            data: data
        })
    }
    async function hisListClick() {
        state.searListShow = !state.searListShow
        await axios.post(lineConParams.value.hisSearchList, {
            pageNum: 1,
            pageSize: 10
        }).then(res => {
            res.data.list.forEach(async item => {
                item.checked = false
                let listData = await getinfosearchlistSwitch({
                    pointIds: item.pointIds,
                    id: item.id
                })
                item.pointIds = listData.data
            })
            state.serXY.x = searListRef.value.offsetLeft - 360
            state.serXY.y = searListRef.value.offsetTop + 60
            state.searList = res.data.list
        })
    }
    // 清楚全部历史操作
    function clearSaveClick(ids) {
        axios.post(lineConParams.value.hisSearchDel, ids)
            .then(res => {
                proxy.$modal.msgSuccess(res.msg);
                hisListClick()
            })
    }
    // 提交选中历史操作
    function searsubmitClick(data) {
        if (data.data && data.rangetime) {
            emits('toolChange', {
                type: 'legendshow',
                data: data.data.pointIds
            })
            emits('toolChange', {
                type: 'dateType',
                data: data.rangetime
            })
            emits('submitPointListClickhis', data.data.pointIds, {})
            state.searListShow = false
        } else {
            proxy.$modal.msgWarning('请先选择一组所要查询的历史数据!或查询时间');
        }
    }
    // 使用模板使用事件功能

    function submitUseTempClick(data) {
        state.drawerShow = false
        emits('submitPointListClick', data.pointIds, {})
    }

    function searcancelClick(val) {
        state.searListShow = val
    }
    // 使用模板
    // 获取使用模版列表数据接口
    function getuseTempList() {
        axios.post(lineConParams.value.tempList, {
            pageNum: 1,
            pageSize: 10
        }).then(res => {
            state.tableData = res.data.list
            res.data.list.forEach(async item => {
                item.checked = false
                let listData = await getinfosearchlistSwitch({
                    pointIds: item.pointIds,
                    id: item.id
                })
                item.pointIds = listData.data
            })
        })
    }

    function usetempClick() {
        state.useTempShow = !state.useTempShow
        getuseTempList()
        state.useTempXY.x = proxy.$refs.usetempRef.offsetLeft - 240
        state.useTempXY.y = proxy.$refs.usetempRef.offsetTop + 60
    }

    function delUseTempClick(ids) {
        axios.post(lineConParams.value.delTemp, ids).then(res => {
            usetempClick()
            proxy.$modal.msgSuccess(res.msg);
        })
    }

    function shuaixuanClick() {
        state.shuaiShow = true
        state.shuaiXY.x = proxy.$refs.shuaixuanRef.offsetLeft
        state.shuaiXY.y = proxy.$refs.shuaixuanRef.offsetTop + 60
    }
    // 搜索选项中选择条件
    function submitSearchResultClick(data, queryObj) {
        state.queryObj = queryObj
        state.acsearList = data
        let timeRangepageValue = []
        if (data.length > 0) {
            state.shuaiShow = false
            data.forEach(item => {
                if (item.type == 'timeRangepage') {
                    timeRangepageValue = item.bindData
                }
            })
            emits('timeRangepageSubmit', timeRangepageValue)
        } else {
            state.shuaiShow = true
        }
        getList(state.queryObj)
    }
    // 清空已选条件全部事件
    function clearAllClick(data) {
        state.acsearList = data
        if (data.length > 0) {
            state.rightList = props.lengedList
            getList(state.queryObj)
        } else {
            state.clearType = 1
            state.rightList = []
            props.lengedList = []
            getList(state.queryObj)
        }

    }
    watchEffect(() => {
        state.drawerShow = props.drawerShow
    })
    onMounted(() => {

        if (props.searList.length > 0) {
            props.searList.forEach(item => {
                item.descList.forEach(itemsub => {
                    if (item.id == 'time') {
                        itemsub.bindData = props.timeRange
                    }
                })
            })
        }
        state.acsearList = props.acSearchList
        getList(state.queryObj)
        state.rightList = props.lengedList
        if (state.queryObj.type == 'A') {
            state.rightList.forEach(item => {
                if (item.pointId.includes('A')) {
                    state.rightListadjust.push(item)
                }
            })
        } else if (state.queryObj.type == 'D') {
            state.rightList.forEach(item => {
                if (item.pointId.includes('D')) {
                    state.rightListadjust.push(item)
                }
            })
        } else if (state.queryObj.type == 'S') {
            state.rightList.forEach(item => {
                if (item.pointId.includes('S')) {
                    state.rightListadjust.push(item)
                }
            })
        }
        // state.rightListadjust = props.lengedList
    })
</script>
<style lang="scss" scoped>
    .btnSpan {
        margin-left: 20px;
    }

    .tableListTotal {
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        border: 1px solid rgba(91, 109, 128, 0.04);
        padding: 8px 10px;
        border-radius: 8px 8px 0px 0px;
        background: rgba(255, 255, 255, 0.6);

        .tableTile {
            font-size: 16px;
            font-weight: 700;

            em {
                font-size: 14px;
                font-style: normal;
                color: rgba(68, 136, 255, 1);
            }
        }

        .tableNum {
            font-size: 16px;
            font-weight: 400;
            color: rgba(62, 70, 79, 0.8);
        }
    }
</style>